package uc;

import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import cn.onekit.CALLBACK;
import cn.onekit.CONFIG;
import cn.onekit.FSO;
import cn.onekit.JSON;
import cn.onekit.android.ACTIVITY;
import co.chuangdian.oflauncher.R;

public class WallpapersView extends GridView {

	public WallpapersView(Context context) {
		super(context);
		init();
	}

	public WallpapersView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	JSONArray wallpapers;
	private CALLBACK<String> callback;

	void init() {
		this.setNumColumns(3);
		this.setHorizontalSpacing(ACTIVITY.dp2px(1));
		this.setVerticalSpacing(ACTIVITY.dp2px(1));
		wallpapers = JSON.parses(CONFIG.get("wallpapers"));
		this.setAdapter(new BaseAdapter() {

			@Override
			public int getCount() {
				return wallpapers.length();
			}

			@Override
			public Object getItem(int position) {
				return null;
			}

			@Override
			public long getItemId(int position) {
				return 0;
			}

			@SuppressLint("ViewHolder")
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				final int width = getWidth();
				String path = getImage(position);
				View view = View.inflate(getContext(), R.layout.uc_wallpapergrid_cell, null);
				view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,width/3));
				ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
				ImageView selectedImageView = (ImageView) view.findViewById(R.id.selectedImageView);
				Bitmap image = FSO.loadImage(path, true);
				imageView.setImageBitmap(image);
				selectedImageView
						.setVisibility(path.equalsIgnoreCase(WallpapersView.this.path) ? View.VISIBLE : View.GONE);
				return view;
			}

		});
		this.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				path = getImage(arg2);
				((BaseAdapter) getAdapter()).notifyDataSetChanged();
				if (callback != null) {
					callback.run(false, path);
				}
			}

		});
	}

	public void setData(CALLBACK<String> callback) {
		this.callback = callback;
	}

	String path;

	String getImage(int index) {
		JSONObject wallpaper = wallpapers.optJSONObject(index);
		return FSO.photos(wallpaper.optString("image")).getPath();
	}
}